package com.sunfield.windpower.activity;

import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.sunfield.baseframe.base.BaseActivity;
import com.sunfield.baseframe.http.HttpResult;
import com.sunfield.baseframe.util.JsonUtil;
import com.sunfield.myglide.MyGlide;
import com.sunfield.windpower.R;
import com.sunfield.windpower.adapter.FileGridAdapter;
import com.sunfield.windpower.bean.NewsInfo;
import com.sunfield.windpower.db.FileDownloadService;
import com.sunfield.windpower.eventbus.CreateCookie;
import com.sunfield.windpower.http.HttpClient;
import com.sunfield.windpower.util.Tools;
import com.sunfield.windpower.view.MyGridView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;

/**
 * Created by wxl on 2017/2/8.
 */
@EActivity(R.layout.activity_news_detail)
public class DoorNewsDetailActivity extends BaseActivity implements CreateCookie.CookieCreatedListener {
    private static final int REQUEST_PERMISSION_STORAGE = 1;
    @ViewById
    TextView tv_title;
    @ViewById
    TextView tv_time;
    @ViewById
    ImageView iv_image;
    @ViewById
    TextView tv_content;
    @ViewById
    MyGridView gv_file;

    @Extra
    String newsId;

    @Bean
    FileGridAdapter adapter;
    @Bean
    HttpClient http;

    NewsInfo newsInfo;

    DownloadManager downloadManager;
    String fileName;

    FileDownloadService downloadService;
    NewsInfo.File fileCache;
    @AfterViews
    void init() {
        gv_file.setAdapter(adapter);
//        tv_title.setText("协和新能源字（2016）130号——关于印发《协和新能源集团供应商管理办法（2016年修订版）》的通知");
//        tv_content.setText("中国共产党第十八届中央纪律检查委员会第七次全体会议今天下午在北京闭幕，现在播送全会公报。 中国共产党第十八届中央纪律检查委员会第七次全体会议于2017年1月6日至8日在北京举行。 出席这次全会的有，中央纪委委员123人，列席266人。 中共中央总书记、国家主席、中央军委主席习近平出席全会并发表重要讲话。李克强、张德江、俞正声、刘云山、王岐山、张高丽等党和国家领导人出席会议。 全会由中央纪律检查委员会常务委员会主持。全会总结2016年纪律检查工作，部署2017年任务，审议通过了王岐山同志代表中央纪委常委会所作的《推动全面从严治党向纵深发展，以优异成绩迎接党的十九大召开》工作报告，审议通过了《中国共产党纪律检查机关监督执纪工 作规则（试行）》。王岐山同志就规则（试行）审议稿向全会作了说明。 全会认真学习、深刻领会习近平总书记重要讲话。一致认为，讲话立意高远、内涵丰富，直面现实、充满自信，蕴含着质朴真挚的为民情怀、许党许国的担当精神，具有深刻思想性和强烈感染力。习近平总书记站在实现党的历史使命的战略全局高度，充分肯定党的十八大以来全 面从严治党取得的显著成效，明确提出当前和今后一个时期工作的总体要求和主要任务。讲话指出，经过全党4年多的努力，党的各级组织管党治党主体责任明显增强，中央八项规定精神得到坚决落实，党的纪律建设全面加强，腐败蔓延势头得到有效遏制，反腐败斗争压倒性态势 已经形成，不敢腐的目标初步实现，不能腐的制度日益完善，不想腐的堤坝正在构筑，党内政治生活呈现新的气象。讲话强调，全面从严治党仍然任重道远，从宽松软走向严紧硬需要经历砥砺淬炼的过程，要继续在常和长、严和实、深和细上下功夫。 全会按照党章规定，选举李书磊同志为中共中央纪律检查委员会常务委员会委员、副书记。");
//        MyGlide.with(this).load(Images.IMAGE_PIC2).into(iv_image);
//
//        gv_file.setAdapter(adapter);
//        adapter.addData(new FileInfo("附件名称.jpg", "21.2KB"));
//        adapter.addData(new FileInfo("大文件.doc", "30.9MB"));

        http.getNewsDetail(newsId);

        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        downloadService = new FileDownloadService(this);
    }

    @Override
    public void onHttpResult(HttpResult result) {
        super.onHttpResult(result);
        if(result.match(http, "getNewsDetail")){
            newsInfo = JsonUtil.GetEntity(JsonUtil.GetJsonObjByLevel(result.getJson(), "data"), NewsInfo.class);

            tv_title.setText(newsInfo.getTitle());
            tv_content.setText(newsInfo.getContent());
            MyGlide.with(this).load(newsInfo.getImage()).into(iv_image);

            adapter.updateData(newsInfo.getFiles());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == REQUEST_PERMISSION_STORAGE ){
            gv_file(fileCache);
        }
    }

    @ItemClick
    void gv_file(NewsInfo.File file){
        if(!checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            fileCache = file;
            requestPermission(REQUEST_PERMISSION_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            return;
        }
//        String url = file.getUrl();
        String url = "http://192.168.4.112:8080/ali.pdf";
        long downloadId = downloadService.getDownloadId(url);
        if(downloadId == -1L) {
            fileName = file.getName();
            toast("开始下载");
            String cookie = Tools.getCookie(url);
            if (TextUtils.isEmpty(cookie)) {
                EventBus.getDefault().post(new CreateCookie(this, url));
            } else {
                download(url);
            }
        }else{
            openFile(downloadId);
        }
    }

    private void download(String url){
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle(fileName);
        request.setDescription("Downloading");
        request.setVisibleInDownloadsUi(true);
        request.addRequestHeader("cookie", Tools.getCookie(url));
        request.setDestinationInExternalFilesDir(this, "file", "file");
        //设置下载的路径
//        request.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory().getAbsolutePath() , "file");
        long downloadId = downloadManager.enqueue(request);
        downloadService.addDownloadInfo(downloadId, url);
    }

    @Override
    public void cookieCreated(String url) {
        download(url);
    }

    //检查下载状态
    private void checkStatus(long downloadId) {
        DownloadManager.Query query = new DownloadManager.Query();
        //通过下载的id查找
        query.setFilterById(downloadId);
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //下载暂停
                case DownloadManager.STATUS_PAUSED:
                    break;
                //下载延迟
                case DownloadManager.STATUS_PENDING:
                    break;
                //正在下载
                case DownloadManager.STATUS_RUNNING:
                    break;
                //下载完成
                case DownloadManager.STATUS_SUCCESSFUL:
                    //下载完成安装APK
                    toast("下载完成");
                    String url = c.getString(c.getColumnIndex(DownloadManager.COLUMN_URI));
                    downloadService.addDownloadInfo(downloadId, url);
                    openFile(downloadId);
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    toast("下载失败");
                    break;
            }
        }
        c.close();
    }

    public void openFile(long downloadId){
        DownloadManager.Query query = new DownloadManager.Query();
        //通过下载的id查找
        query.setFilterById(downloadId);
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //设置intent的Action属性
            intent.setAction(Intent.ACTION_VIEW);
            //设置intent的data和Type属性。
            Uri uri = Uri.parse(c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
            String type = c.getString(c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
            intent.setDataAndType(uri, type);
            //跳转
            try {
                startActivity(intent); //这里最好try一下，有可能会报错。 //比如说你的MIME
            } catch (Exception e) {
                toast("您未安装打开此文件的应用！");
                e.printStackTrace();
            }

//            try {
//                ContentResolver cr = getContentResolver();
//                ParcelFileDescriptor pfd = cr.openFileDescriptor(Uri.parse(c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))), "rwt");
////                        ParcelFileDescriptor pfd = downloadManager.openDownloadedFile(downloadId);
//                FileDescriptor fd = pfd.getFileDescriptor();
//                Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fd);
//                toast("" + (bitmap == null));
//                iv_image.setImageBitmap(bitmap);
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
        }
        c.close();
    }


    //广播监听下载的各个状态
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            checkStatus(downloadId);
        }
    };
}
